#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <config.h>
#include <weather.h>
#include <photo_manager.h>

PT_displayOpr g_ptDisplayDevice;
PT_networkOpr g_ptNetwork;
PT_networkOpr g_ptNetServer;

static void exit_handler(int s)
{
	fprintf(stdout,"get signal %d\n",s);
	displayExit();
	fprintf(stdout,"displayExit sucess\n");
	weatherThreadExit();
	fprintf(stdout,"weatherThreadExit sucess\n");
	WeatherServerExit();
	fprintf(stdout,"WeatherServerExit sucess\n");
	inputExit();
	fprintf(stdout,"inputExit sucess\n");

	exit(0);
}

int main(int argc, char **argv)
{
	int ret;
	struct sigaction act;

	/*******************signal******************/
	act.sa_handler = exit_handler;
	sigemptyset(&act.sa_mask);
	sigaddset(&act.sa_mask,SIGINT);
	sigaddset(&act.sa_mask,SIGQUIT);
	sigaddset(&act.sa_mask,SIGTERM);
	act.sa_flags =0;

	sigaction(SIGINT,&act,NULL);
	sigaction(SIGQUIT,&act,NULL);
	sigaction(SIGTERM,&act,NULL);
	
	/****************display*********************/
	ret = displayInit();
	if(ret <0)
	{
		fprintf(stderr,"displayInit error\n");
		exit(1);
	}
	showDisplayOpr();
	
	g_ptDisplayDevice = getDisplayOpr("fb");
	if(g_ptDisplayDevice ==NULL)
	{
		fprintf(stderr,"getDisplayOpr error\n");
		exit(1);
	}

	/******************input*******************/
	ret = inputInit();
	if(ret <0)
	{
		fprintf(stderr,"inputInit error\n");
		exit(1);
	}
	showInputOpr();
	
	ret = initAllInputOpr();
	if(ret <0)
	{
		fprintf(stderr,"initAllInputOpr error\n");
		exit(1);
	}

	/*****************photo********************/
	ret = initPhotoOpr();
	if(ret <0)
	{
		fprintf(stderr,"initPhotoOpr error\n");
		exit(1);
	}
	showPhotoOpr();

	/******************network*******************/
	ret = initNetWork();
	if(ret <0)
	{
		fprintf(stderr,"initNetWork error\n");
		exit(1);
	}
	showNetWork();
	
	g_ptNetwork = selectNetWork("client");
	if(g_ptNetwork ==NULL)
	{
		fprintf(stderr,"selectNetWork client error\n");
		exit(1);
	}

	g_ptNetServer = selectNetWork("server");
	if(g_ptNetwork ==NULL)
	{
		fprintf(stderr,"selectNetWork server error\n");
		exit(1);
	}

	/****************启动天气查询线程*********************/
	ret = weatherThreadInit();
	if(ret <0)
	{
		fprintf(stderr,"weatherThreadInit error\n");
		exit(1);
	}

	/*****************启动天气设置服务******************/
	ret = WeatherServerInit();
	if(ret <0)
	{
		fprintf(stderr,"WeatherServerInit error\n");
		exit(1);
	}

	/******************pages**********************/
	ret = initPages();
	if(ret <0)
	{
		fprintf(stderr,"initPages error\n");
		exit(1);
	}
	showPages();

	/******************mainPage**********************/
	usleep(500000); //延时500ms
	runPage("mainpage");

	return 0;
}

